package top.lishuoboy.boot03web.a4;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lishuoboy.boot03web.a4.bean.User;

import java.util.Map;

/**
 * @author lishuoboy
 * @date 2022/1/25 11:27
 */
@Slf4j
@Controller
@RequestMapping("/a4")
public class ReturnTypeController {
    private final static Map map = MapUtil.builder().put("name", "张三").put("age", 18).build();

    /**
     * 返回json或xml
     * 1、默认返回json。
     * 2、返回xml支持，需添加依赖 jackson-dataformat-xml
     * 3、通过produces强制设置返回类型json或xml。如果没有设置将走内容协商流程，根据请求头的accept的权重优先级返回。
     * accept=application/xml
     * accept=application/json
     * 另外，为了方便内容协商，开启基于请求参数的内容协商功能
     * spring.mvc.contentnegotiation.favor-parameter=true
     * http://localhost:8080/a4/json_xml?format=xml
     * http://localhost:8080/a4/json_xml?format=json
     * http://localhost:8080/a4/json_xml
     */
    @RequestMapping(value = "/json_xml", produces = {})
    @ResponseBody
    private Object json_xml() {
        return User.builder().id("111").name("张三").build();
    }


    /**
     * 强制返回xml。需添加依赖 jackson-dataformat-xml
     * http://localhost:8080/a4/json_xml
     */
    @RequestMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    private Object xml() {
        return map;
    }

    /**
     * 强制返回json。需添加依赖 jackson-dataformat-xml
     * http://localhost:8080/a4/json_xml
     */
    @RequestMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    private Object json() {
        return map;
    }


}
